package com.kk.utils;

import javafx.application.Platform;
import javafx.scene.web.WebEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * the class of javafx-nesting-ui
 *
 * <p>
 * .
 *
 * @author little_lunatic
 * @date 2023-01-19
 */
public class AppHandler {
    public static final AppHandler INSTANCE = new AppHandler();
    private static final Logger LOGGER = LoggerFactory.getLogger(AppHandler.class);

    private static volatile boolean startup = false;

    @Autowired
    private WebEngine webEngine;
    public static void setStartup(boolean startup) {
        AppHandler.startup = startup;
    }
    public static boolean isStartup() {
        return startup;
    }

    private AppHandler() {
    }
    public static void initialize() {
    }

    public static void exit() {
        System.exit(0);
    }


    private void callbackByFrame(String frame, String method, String... args) {
        String script = "window.";
        if (!StringUtils.isEmpty(frame)) {
            script += "frames[" + frame + "].";
        }
        script += method + "(";

        if (args != null && args.length > 0) {
            for (String arg : args) {
                script += "'" + arg + "',";
            }
            script = script.substring(0, script.lastIndexOf(","));
        }
        script += ")";

        excuteScript(script);
    }

    public static void callback(String method, String... args) {
        INSTANCE.callbackByFrame(null, method, args);
    }

    private void excuteScript(String targetScript) {
        LOGGER.debug("execute script==>" + targetScript);
        Platform.runLater(() -> webEngine.executeScript(targetScript));
    }
}